package Share;

import java.io.IOException;
import java.net.*;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.util.concurrent.atomic.AtomicBoolean;

import javax.crypto.NoSuchPaddingException;

public class ConnectionWaiter {
	private ServerSocket serverSocket;
	private AtomicBoolean stopped = new AtomicBoolean(false);
	private Certificate certificate;
	private PrivateKey key;
	public ConnectionWaiter(int port, Certificate certificate, PrivateKey key) throws IOException
	{
		serverSocket = new ServerSocket(port);
		this.certificate = certificate;
		this.key = key;
	}
	
	public Session accept() throws IOException, InvalidKeyException, SignatureException, InvalidKeySpecException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, NoSuchPaddingException
	{
		Socket client = serverSocket.accept();
		if(stopped.get())
		{
			if(client != null)
			{
				try
				{
					client.close();
				}
				catch(IOException error)
				{
					
				}
			}
			return null;
		}
		else
			return new Session(client, certificate, key);
	}
	
	public void close() throws IOException
	{
		stopped.set(true);
		serverSocket.close();
	}
}
